<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="房东姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入房东姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机" prop="phonenumber">
        <el-input
          v-model="queryParams.phonenumber"
          placeholder="请输入手机"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
        >导入</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="landlordList" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="房东姓名" align="center" prop="nickName" />
      <el-table-column label="手机" align="center" prop="phonenumber" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="用户ID" align="center" prop="userId" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-house"
            @click="handleHouseManage(scope.row)"
          >账单管理</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改房东对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="房东姓名" prop="nickName">
          <el-input v-model="form.nickName" placeholder="请输入房东姓名" />
        </el-form-item>
        <el-form-item label="手机" prop="phonenumber">
          <el-input v-model="form.phonenumber" placeholder="请输入手机" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 房东导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="500px" append-to-body :close-on-click-modal="false">
      <div class="import-container">
        <div class="import-tips" v-if="!upload.isUploading && !upload.isProcessing">
          <p>请先下载房东导入模板，按照模板格式填写数据后导入：</p>
          <el-button type="text" icon="el-icon-download" @click="importTemplate">下载模板</el-button>
        </div>

        <!-- 文件选择区域 -->
        <div v-if="!upload.isUploading && !upload.isProcessing">
          <el-divider content-position="center">选择文件</el-divider>
          <div class="file-info" v-if="uploadFileName">
            <i class="el-icon-document"></i>
            <span>{{ uploadFileName }}</span>
            <el-button type="text" icon="el-icon-delete" @click="clearUploadFile">清除</el-button>
          </div>
          <div class="upload-area" v-else @click="triggerFileInput">
            <input type="file" ref="fileInput" accept=".xlsx, .xls" style="display: none;" @change="handleFileChange" />
            <i class="el-icon-upload"></i>
            <div class="upload-text">点击选择Excel文件</div>
            <div class="upload-tip">仅支持.xlsx和.xls格式</div>
          </div>
        </div>

        <!-- 导入进度区域 -->
        <div v-if="upload.isUploading" class="import-progress">
          <div class="progress-header">
            <i class="el-icon-loading"></i>
            <span>{{ upload.statusText }}</span>
          </div>

          <el-progress
            :percentage="upload.progress"
            :status="upload.progressStatus || undefined"
            :stroke-width="12"
            :show-text="true"
          ></el-progress>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="submitImport"
          :loading="upload.isUploading"
          :disabled="!uploadFile || upload.isUploading"
        >
          {{ upload.isUploading ? '导入中...' : '确 定' }}
        </el-button>
        <el-button
          @click="closeImportDialog"
          :disabled="upload.isUploading"
        >
          {{ upload.isUploading ? '处理中...' : '取 消' }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: "Landlord",
  data() {
    // 手机号验证规则
    const validatePhone = (rule, value, callback) => {
      if (value && !/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error("请输入正确的手机号码"));
      } else {
        callback();
      }
    };

    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 房东表格数据
      landlordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        phonenumber: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        nickName: [
          { required: true, message: "房东姓名不能为空", trigger: "blur" }
        ],
        phonenumber: [
          { required: true, message: "手机号码不能为空", trigger: "blur" },
          { validator: validatePhone, trigger: "blur" }
        ]
      },
      // 上传的文件
      uploadFile: null,
      // 上传文件名
      uploadFileName: "",
      // 房东导入参数
      upload: {
        // 是否显示弹出层（房东导入）
        open: false,
        // 弹出层标题（房东导入）
        title: "",
        // 是否正在导入
        isUploading: false,
        // 是否正在处理
        isProcessing: false,
        // 当前状态文本
        statusText: "准备上传文件...",
        // 进度百分比
        progress: 0,
        // 进度状态
        progressStatus: null
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询房东列表 */
    getList() {
      this.loading = true
      request({
        url: '/system/role/authUser/allocatedListNoDataScope',
        method: 'get',
        params: {
          pageNum: this.queryParams.pageNum,
          pageSize: this.queryParams.pageSize,
          roleId: 100,
          nickName: this.queryParams.name,
          ...this.queryParams
        }
      }).then(response => {
        // 适配新接口字段
        this.landlordList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(()=>{this.loading=false})
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        nickName: null,
        phonenumber: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加房东"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      // 正确映射字段
      this.form = {
        userId: row.userId,
        nickName: row.nickName,
        phonenumber: row.phonenumber,
        createBy: row.createBy,
        createTime: row.createTime,
        updateBy: row.updateBy,
        updateTime: row.updateTime,
        remark: row.remark
      }
      this.open = true
      this.title = "修改房东"
    },
    /** 提交按钮 */
    submitForm() {
      console.log('submitForm被调用了')
      debugger
      this.$refs["form"].validate(valid => {
        if (valid) {
          debugger
          console.log(this.form)
          if (this.form.userId != null) {
            this.updateLandlord(this.form)
          } else {
            this.addLandlord(this.form)
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除房东编号为"' + ids + '"的数据项？').then(function() {
        return request({
          url: '/system/landlord/' + ids,
          method: 'delete'
        })
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/landlord/export', {
        ...this.queryParams
      }, `landlord_${new Date().getTime()}.xlsx`)
    },
    /** 账单管理按钮操作 */
    handleHouseManage(row) {
      this.$router.push({
        path: '/house',
        query: {
          landlordName: row.nickName
        }
      })
    },
    /** 添加房东 */
    addLandlord(data) {
      // 新增房东接口参数适配
      const submitData = {
        userName: data.phonenumber,
        nickName: data.nickName,
        password: '123456',
        phonenumber: data.phonenumber,
        status: '0',
        postIds: [],
        roleIds: [100]
      }
      request({
        url: '/system/user',
        method: 'post',
        data: submitData
      }).then(response => {
        this.$modal.msgSuccess("新增成功")
        this.open = false
        this.getList()
      })
    },
    /** 修改房东 */
    updateLandlord(data) {
      // 修改房东接口参数适配
      const submitData = {
        userId: data.userId,
        userName: data.phonenumber,
        nickName: data.nickName,
        phonenumber: data.phonenumber,
        status: '0',
        postIds: [],
        roleIds: [100]
      }
      request({
        url: `/system/user`,
        method: 'put',
        data: submitData
      }).then(response => {
        this.$modal.msgSuccess("修改成功")
        this.open = false
        this.getList()
      })
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "房东导入"
      this.upload.open = true
      this.uploadFile = null
      this.uploadFileName = ""
      this.resetUploadState()
    },
    /** 下载模板操作 */
    importTemplate() {
      this.downloadTemplatePost("/system/user/importNicknameTemplate", "房东导入模板.xlsx")
    },
    // 触发文件选择
    triggerFileInput() {
      this.$refs.fileInput.click()
    },
    // 处理文件选择
    handleFileChange(e) {
      const files = e.target.files
      if (files && files.length > 0) {
        this.uploadFile = files[0]
        this.uploadFileName = files[0].name
      }
    },
    // 清除选择的文件
    clearUploadFile() {
      this.uploadFile = null
      this.uploadFileName = ""
      if (this.$refs.fileInput) {
        this.$refs.fileInput.value = ""
      }
    },
    // 提交导入请求
    submitImport() {
      if (!this.uploadFile) {
        this.$message.warning("请先选择要上传的Excel文件")
        return
      }

      this.upload.isUploading = true
      this.upload.statusText = "正在导入数据..."
      this.upload.progress = 50

      // 创建FormData对象
      const formData = new FormData()
      formData.append('file', this.uploadFile)

      // 调用导入API
      request({
        url: '/system/user/importNicknameData',
        method: 'post',
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        responseType: 'blob'
      }).then(response => {
        this.upload.isUploading = false
        this.upload.progress = 100
        this.upload.statusText = "导入完成，正在下载结果文件..."
        this.upload.progressStatus = 'success'

        // 直接下载返回的文件流
        const url = window.URL.createObjectURL(response)
        const a = document.createElement('a')
        a.href = url
        a.download = `房东导入结果_${new Date().getTime()}.xlsx`
        document.body.appendChild(a)
        a.click()
        window.URL.revokeObjectURL(url)
        document.body.removeChild(a)

        this.$message.success("导入完成，结果文件已下载")

        // 刷新列表
        this.getList()

        // 2秒后关闭对话框
        setTimeout(() => {
          this.closeImportDialog()
        }, 2000)
      }).catch(error => {
        this.upload.isUploading = false
        this.upload.progress = 0
        this.upload.statusText = "导入失败"
        this.upload.progressStatus = 'exception'

        console.error('导入失败:', error)
        let errorMessage = "导入失败"

        if (error.response) {
          // 如果有响应，尝试解析错误信息
          if (error.response.data && error.response.data.type === 'application/json') {
            // 如果返回的是JSON错误信息，需要转换
            const reader = new FileReader()
            reader.onload = () => {
              try {
                const errorData = JSON.parse(reader.result)
                errorMessage = errorData.msg || "导入失败"
                this.$message.error(errorMessage)
              } catch (e) {
                this.$message.error("导入失败，请检查文件格式")
              }
            }
            reader.readAsText(error.response.data)
          } else {
            errorMessage = error.response.statusText || "导入失败"
            this.$message.error(errorMessage)
          }
        } else {
          errorMessage = error.message || "网络错误"
          this.$message.error(errorMessage)
        }
      })
    },
    // 重置上传状态
    resetUploadState() {
      this.upload.isUploading = false
      this.upload.isProcessing = false
      this.upload.statusText = "准备上传文件..."
      this.upload.progress = 0
      this.upload.progressStatus = null
    },
    // 关闭导入对话框
    closeImportDialog() {
      this.upload.open = false
      this.resetUploadState()
      this.clearUploadFile()
    }
  }
}
</script>

<style scoped>
/* 导入对话框样式 */
.import-container {
  padding: 10px 0;
}

.import-tips {
  margin-bottom: 15px;
}

.upload-area {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  text-align: center;
  padding: 30px 0;
  margin: 10px 0;
}

.upload-area:hover {
  border-color: #409EFF;
}

.upload-area .el-icon-upload {
  font-size: 40px;
  color: #c0c4cc;
  margin-bottom: 10px;
}

.upload-text {
  color: #606266;
  font-size: 14px;
  margin-bottom: 5px;
}

.upload-tip {
  color: #909399;
  font-size: 12px;
}

.file-info {
  display: flex;
  align-items: center;
  padding: 10px;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  margin: 10px 0;
  background-color: #f9f9f9;
}

.file-info i {
  color: #909399;
  margin-right: 8px;
  font-size: 18px;
}

/* 导入进度样式 */
.import-progress {
  padding: 20px 0;
}

.progress-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  font-size: 16px;
  color: #606266;
}

.progress-header i {
  margin-right: 8px;
  color: #409EFF;
  animation: rotate 2s linear infinite;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 进度条样式调整 */
.el-progress {
  margin: 10px 0;
}

.el-progress__text {
  font-weight: bold;
}
</style>
